package top.huntwolf.admin.service;

import com.auth0.jwt.exceptions.JWTDecodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.dao.UserDao;
import top.huntwolf.admin.pojo.User;
import top.huntwolf.admin.utils.RedisUtil;
import top.huntwolf.admin.utils.TokenUtil;

import java.util.List;

@Service
@Transactional
public class HistoryService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisUtil redisUtil;


    public void addSearchHistory(String content){
        String token = "";
        try {
            token = TokenUtil.getTokenOpenId();
        }catch (NullPointerException | JWTDecodeException e){
            //没有登录
            return;
        }

        User user = userDao.selectUserById(token);
        String openId = user.getOpenId();

        String key = "history_" + openId;

        redisUtil.lRemove(key,0,content);
        redisUtil.lRightSet(key,content);
        redisUtil.lTrim(key,0,9);

    }

    public List<Object> SearchHistory(){

        String token = "";
        try {
            token = TokenUtil.getTokenOpenId();
        }catch (NullPointerException | JWTDecodeException e){
            //没有登录
            return null;
        }
        User user = userDao.selectUserById(TokenUtil.getTokenOpenId());
        String openId = user.getOpenId();

        String key = "history_" + openId;
        List<Object> contents = redisUtil.lGet(key,0,9);

        return contents;
    }

    public void deleteHistory(){
        String openId = "";
        try {
            openId = TokenUtil.getTokenOpenId();
        }catch (NullPointerException | JWTDecodeException e){
            //没有登录
            return;
        }
        String key = "history_" + openId;
        redisUtil.del(key);
    }

    public void deleteHistory(String content){

        String openId = "";
        try {
            openId = TokenUtil.getTokenOpenId();
        }catch (NullPointerException | JWTDecodeException e){
            //没有登录
            return;
        }
        String key = "history_" + openId;
        redisUtil.lRemove(key,0,content);

    }


}
